/*
 * Copyright 2009 rashaguo <rashaguo@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#include "natnetwork.h"
#include "utils/logger.h"

#include <pjlib.h>

#include <QtNetwork/QHostAddress>

NatNetwork::NatNetwork()
{
    m_localIP = "";
    m_natIP = "";
    m_natType = NatNetwork::Unknown;
    m_isLocalResolved = false;
    m_isNatResolved = false;
    m_isNat = false;
}

NatNetwork::~NatNetwork()
{
    m_localIP = "";
    m_natIP = "";
    m_natType = NatNetwork::Unknown;
    m_isLocalResolved = false;
    m_isNatResolved = false;
    m_isNat = false;
}

void NatNetwork::init()
{
    resolveLocal();
    resolveNat();
}

void NatNetwork::resolveLocal()
{
    pj_sockaddr add;
    pj_status_t status;

    status = pj_gethostip(pj_AF_INET(), &add);
    if(status != PJ_SUCCESS) return;

   // char *host_name = pj_gethostname()->str;
    m_localIP = std::string(pj_inet_ntoa(add.ipv4.sin_addr));
    LOG_DEBUG("get local ip: %s", m_localIP.c_str());
    m_isLocalResolved = true;

}

void NatNetwork::resolveNat()
{
    m_isNat = false;
}

std::string NatNetwork::getLocalIP()
{
    if(!m_isLocalResolved) resolveLocal();
    return m_localIP;
}

std::string NatNetwork::getNatIP()
{
    if(!m_isNatResolved) resolveNat();

    if(!m_isNat)
    {
        LOG_DEBUG("Not in NAT, return local IP");
        m_natIP = getLocalIP();
        return m_natIP;
    }
    return m_natIP;
}

bool NatNetwork::isInNat()
{
    return m_isNat;
}

enum NatNetwork::NatType NatNetwork::getNatType()
{
    return m_natType;
}

std::string NatNetwork::getNatPort(std::string local_port)
{
    if(!m_isNatResolved) resolveNat();
    if(!m_isNat)
    {
        LOG_DEBUG("Not in NAT, return local port");
        return local_port;
    }

    return "";
}

// TBD
void NatNetwork::sendTestPacket()
{
}

bool NatNetwork::isReachable()
{
}
